package com.gxa.service.impl;

import com.gxa.common.R;
import com.gxa.mapper.premissionMapper;
import com.gxa.pojo.Menu;
import com.gxa.pojo.Premission;
import com.gxa.service.menuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiejinfeng
 * @create 2021-06-09 10:27
 * @descrip:
 */
@Service
public class menuServiceImpl implements menuService {

    @Autowired
    private premissionMapper mapper;

    @Override
    public R munuList(HttpSession session) {
        Boolean isSuper = (Boolean) session.getAttribute("isSuper");


        List<Premission> premissions;

        if (isSuper) {
             premissions = mapper.findAll();
        }else {
             premissions = (List<Premission>) session.getAttribute("permissions");
        }

        List<Menu> menus = getMenus(premissions);

        return new R(200,"成功",menus);
    }

    private List<Menu> getMenus(List<Premission> all){
        List<Menu> menus = new ArrayList<>();

        for (Premission premission : all) {

            if (premission.getParentId().equals(0) && premission.getPremissionLevel().equals(1) && premission.getIsMenu().equals(1)){
                menus.add(new Menu(premission.getPremissionId(),premission.getPremissionName(),premission.getPremissionUrl(),premission.getParentId()));
            }
        }
        for (Menu menu : menus) {

            List<Menu> subMenus = new ArrayList<>();

            for (Premission premission : all) {
                if (premission.getParentId().equals(menu.getMenuId()) && premission.getPremissionLevel().equals(2) && premission.getIsMenu().equals(1) ){
                    subMenus.add(new Menu(premission.getPremissionId(),premission.getPremissionName(),premission.getPremissionUrl(),premission.getParentId()));
                }
            }
            menu.setSubMenus(subMenus);
        }
        return menus;

    }
}
